package com.rn.gypsophila.netty.websocket;

import com.rn.gypsophila.netty.common.ChannelSupervise;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * WebSocket 处理器
 *
 * @author 然诺
 * @date 2021/4/21
 */
@Slf4j
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 返回应答消息
        String request = ((TextWebSocketFrame) msg).text();
        log.debug("服务端收到消息：" + request);
        TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString() + ctx.channel().id() + " : " + request);
        // 群发
        ChannelSupervise.sendGroup(tws);
        // 返回【谁发的发给谁】
//        ctx.channel().writeAndFlush(tws);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("客户端加入连接：" + ctx.channel().id());
        ChannelSupervise.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("客户端断开连接：" + ctx.channel().id());
        ChannelSupervise.removeChannel(ctx.channel());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

}
